package com.ruoyi.web.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MSWordPoi4;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.enterprise.domain.*;
import com.ruoyi.enterprise.service.*;
import com.ruoyi.environment.domain.EnvShouxu;
import com.ruoyi.environment.service.IEnvShouxuNewService;
import com.ruoyi.facilities.domain.TfGasgc;
import com.ruoyi.facilities.domain.TfNoisegc;
import com.ruoyi.facilities.domain.TfWatergc;
import com.ruoyi.facilities.service.ITfGasgcService;
import com.ruoyi.facilities.service.ITfNoisegcService;
import com.ruoyi.facilities.service.ITfWatergcService;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.pollutant.domain.OutletExhaust;
import com.ruoyi.pollutant.domain.OutletNoise;
import com.ruoyi.pollutant.domain.OutletSolid;
import com.ruoyi.pollutant.domain.OutletWater;
import com.ruoyi.pollutant.service.IOutletExhaustService;
import com.ruoyi.pollutant.service.IOutletNoiseService;
import com.ruoyi.pollutant.service.IOutletSolidService;
import com.ruoyi.pollutant.service.IOutletWaterService;
import com.ruoyi.safe.domain.*;
import com.ruoyi.safe.service.*;
import com.ruoyi.system.domain.IndustryEntity;
import com.ruoyi.system.domain.SysFileInfo;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.domain.vo.MessageTemplate;
import com.ruoyi.system.service.*;
import com.ruoyi.visit.domain.LetterVisit;
import com.ruoyi.visit.service.ILetterVisitNewService;
import com.ruoyi.visit.service.ILetterVisitService;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 通用请求处理
 *
 * @author yxf
 */
@RestController
public class CommonController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysFileInfoService sysFileInfoService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ILetterVisitService letterVisitService;
    @Autowired
    private IEnterpriseArchiveService enterpriseArchiveService;
    @Autowired
    private ISysNoticeService sysNoticeService;
    @Autowired
    private IRiskUnitService riskUnitService;
    @Autowired
    private ISewagePermitService sewagePermitService;
    @Autowired
    private IProjectConstructionService projectConstructionService;
    @Autowired
    private IProductionProcessService productionProcessService;
    @Autowired
    private ITfGasgcService tfGasgcService;
    @Autowired
    private ITfNoisegcService tfNoisegcService;
    @Autowired
    private ITfWatergcService tfWatergcService;
    @Autowired
    private IOutletExhaustService outletExhaustService;
    @Autowired
    private IOutletNoiseService outletNoiseService;
    @Autowired
    private IOutletSolidService outletSolidService;
    @Autowired
    private IOutletWaterService outletWaterService;
    @Autowired
    private IChemicalHandlingService chemicalHandlingService;
    @Autowired
    private IEmergencyRescueService emergencyRescueService;
    @Autowired
    private IRiskPreSysService riskPreSysService;
    @Autowired
    private ISurroundingEnvService surroundingEnvService;

    @Autowired
    private IFileMakerService fileMakerService;


    @Autowired
    private ILetterVisitNewService letterVisitNewService;

    @Autowired
    private IEnvShouxuNewService envShouxuNewService;


    @Autowired
    private IndustryService industryService;

    @Autowired
    private ISysChinaService sysChinaService;


    @Autowired
    private SmsSerivce smsSerivce;

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private IEpNewService epNewService;



    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;

            SysFileInfo sysFileInfo = new SysFileInfo();
            sysFileInfo.setFileName(file.getName() + File.separator + file.getOriginalFilename());
            sysFileInfo.setFilePath(url);
            sysFileInfoService.insertSysFileInfo(sysFileInfo);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
    /**
     * 企业注册 //支持手机号、用户名、邮箱
     */
    @Log(title = "企业注册", businessType = BusinessType.INSERT)
    @PostMapping("/common/enterpriseAdd")
    public AjaxResult enterpriseAdd(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增企业用户'" + user.getUserName() + "'失败，用户名已存在");
        }
        user.setCreateBy(user.getUserName());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        Long[] xx = new Long[]{Long.parseLong("100")};
        user.setRoleIds(xx);
        EnterpriseArchive enterpriseArchive = new EnterpriseArchive();
        enterpriseArchive.setEpUserName(user.getUserName());
        enterpriseArchiveService.insertEnterpriseArchive(enterpriseArchive);
        return AjaxResult.success(userService.insertUser(user));
    }



    /**
     * 根据当前登录用户获取企业基本信息详细信息
     */
    @Log(title = "根据当前登录用户获取企业基本信息", businessType = BusinessType.OTHER)
    @GetMapping(value = "/common/getEpByUser")
    public AjaxResult getInfo(@RequestParam("epUserName") String epUserName)
    {
        EnterpriseArchive enterpriseArchive = enterpriseArchiveService.selectEnterpriseArchiveByUserName(epUserName);
        return AjaxResult.success(enterpriseArchive);
    }
    /**
     * 信访投诉注册
     */
    @Log(title = "信访投诉注册", businessType = BusinessType.INSERT)
    @PostMapping("/common/letterAdd")
    public AjaxResult add(@RequestBody LetterVisit letterVisit) {
        return AjaxResult.success(letterVisitService.insertLetterVisit(letterVisit));
    }
    /**
     * 获取通知公告详细信息
     */
    @GetMapping(value = "/common/notice/{noticeId}")
    public AjaxResult getInfo(@PathVariable("noticeId") Integer noticeId)
    {
        return AjaxResult.success(sysNoticeService.selectSysNoticeById(noticeId));
    }
    /**
     * 查询通知公告列表
     */
    @GetMapping("/common/notice/list")
    public TableDataInfo list(SysNotice sysNotice)
    {
        startPage();
        List<SysNotice> list = sysNoticeService.selectSysNoticeList(sysNotice);
        return getDataTable(list);
    }
    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @PostMapping("/common/notice/edit")
    public AjaxResult edit(@RequestBody SysNotice sysNotice)
    {
        return toAjax(sysNoticeService.updateSysNotice(sysNotice));
    }
    @Log(title = "企业基本信息导入", businessType = BusinessType.IMPORT)
    @PostMapping("/common/enterprise/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport,String userName) throws Exception
    {
        ExcelUtil<EnterpriseArchive> util = new ExcelUtil<EnterpriseArchive>(EnterpriseArchive.class);
        List<EnterpriseArchive> epList = util.importExcel(file.getInputStream());
        String message = enterpriseArchiveService.importEnterPrise(epList, updateSupport, userName);
        return AjaxResult.success(message);
    }
    /**
     * 查询企业列表
     */
    @GetMapping("/common/enterprise/list")
    public TableDataInfo list(EnterpriseArchive enterpriseArchive)
    {
        startPage();
        List<EnterpriseArchive> list = enterpriseArchiveService.selectEnterpriseArchiveList(enterpriseArchive);
        return getDataTable(list);
    }


    /**
     * 查询企业规模大小数量
     */
    @GetMapping("/common/enterprise/qygm")
    public AjaxResult qygm()
    {
        EnterpriseArchive guiShang = new EnterpriseArchive();
        guiShang.setEpScale("1");
        List<EnterpriseArchive> guiShangList = enterpriseArchiveService.selectEnterpriseArchiveList(guiShang);


        EnterpriseArchive guiXia = new EnterpriseArchive();
        guiXia.setEpScale("2");
        List<EnterpriseArchive> guiXiaList = enterpriseArchiveService.selectEnterpriseArchiveList(guiXia);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("shang",guiShangList.size());
        jsonObject.put("xia",guiXiaList.size());
        return AjaxResult.success(jsonObject);
    }


    /**
     * 查询风险单元详情
     */
    @GetMapping(value = "common/safe/unit/{epId}")
    public AjaxResult getInfo(@PathVariable("epId") Long epId)
    {
        RiskUnit riskUnit = new RiskUnit();
        riskUnit.setEpId(epId);
        List<RiskUnit> unitList = riskUnitService.selectRiskUnitList(riskUnit);
        System.out.println(unitList.size());
        if(!Collections.isEmpty(unitList)){
            return AjaxResult.success(unitList.get(0));
        }
        return null;

    }


    /**
     * 分页查询排污许可证
     */
    @GetMapping("/common/enterprise/sewagePermit")
    public TableDataInfo sewagePermit(SewagePermit sewagePermit)
    {
        startPage();
        List<SewagePermit> sewagePermitList = sewagePermitService.selectSewagePermitList(sewagePermit);
        return getDataTable(sewagePermitList);
    }

    @GetMapping("/common/enterprise/projectConstruction")
    public TableDataInfo projectConstruction(ProjectConstruction projectConstruction)
    {
        startPage();
        List<ProjectConstruction> projectConstructionList = projectConstructionService.selectProjectConstructionList(projectConstruction);
        return getDataTable(projectConstructionList);
    }

    @GetMapping("/common/enterprise/productionProcess")
    public TableDataInfo productionProcess(ProductionProcess productionProcess)
    {
        startPage();
        List<ProductionProcess> processList = productionProcessService.selectProductionProcessList(productionProcess);
        return getDataTable(processList);
    }

    @GetMapping("/common/enterprise/tfGasgc")
    public TableDataInfo tfGasgc(TfGasgc tfGasgc)
    {
        startPage();
        List<TfGasgc> tfGasgcList = tfGasgcService.selectTfGasgcList(tfGasgc);
        return getDataTable(tfGasgcList);
    }

    @GetMapping("/common/enterprise/tfNoisegc")
    public TableDataInfo tfNoisegc(TfNoisegc tfNoisegc)
    {
        startPage();
        List<TfNoisegc> tfNoisegcList = tfNoisegcService.selectTfNoisegcList(tfNoisegc);
        return getDataTable(tfNoisegcList);
    }

    @GetMapping("/common/enterprise/tfWatergc")
    public TableDataInfo tfWatergc(TfWatergc tfWatergc)
    {
        startPage();
        List<TfWatergc> tfWatergcList = tfWatergcService.selectTfWatergcList(tfWatergc);
        return getDataTable(tfWatergcList);
    }

    @GetMapping("/common/enterprise/outletExhaust")
    public TableDataInfo outletExhaust(OutletExhaust outletExhaust)
    {
        startPage();
        List<OutletExhaust> outletExhaustList = outletExhaustService.selectOutletExhaustList(outletExhaust);
        return getDataTable(outletExhaustList);
    }

    @GetMapping("/common/enterprise/outletNoise")
    public TableDataInfo outletNoise(OutletNoise outletNoise)
    {
        startPage();
        List<OutletNoise> outletNoiseList = outletNoiseService.selectOutletNoiseList(outletNoise);
        return getDataTable(outletNoiseList);
    }

    @GetMapping("/common/enterprise/outletSolid")
    public TableDataInfo outletSolid(OutletSolid outletSolid)
    {
        startPage();
        List<OutletSolid> outletSolidList = outletSolidService.selectOutletSolidList(outletSolid);
        return getDataTable(outletSolidList);
    }

    @GetMapping("/common/enterprise/outletWater")
    public TableDataInfo outletWater(OutletWater outletWater)
    {
        startPage();
        List<OutletWater> outletWaterList = outletWaterService.selectOutletWaterList(outletWater);
        return getDataTable(outletWaterList);
    }

    @GetMapping("/common/enterprise/chemicalHandling")
    public TableDataInfo chemicalHandling(ChemicalHandling chemicalHandling)
    {
        startPage();
        List<ChemicalHandling> chemicalHandlingList = chemicalHandlingService.selectChemicalHandlingList(chemicalHandling);
        return getDataTable(chemicalHandlingList);
    }

    @GetMapping("/common/enterprise/emergencyRescue")
    public TableDataInfo emergencyRescue(EmergencyRescue emergencyRescue)
    {
        startPage();
        List<EmergencyRescue> emergencyRescueList = emergencyRescueService.selectEmergencyRescueList(emergencyRescue);
        return getDataTable(emergencyRescueList);
    }

    @GetMapping("/common/enterprise/riskPreSys")
    public TableDataInfo riskPreSys(RiskPreSys riskPreSys)
    {
        startPage();
        List<RiskPreSys> riskPreSysList = riskPreSysService.selectRiskPreSysList(riskPreSys);
        return getDataTable(riskPreSysList);
    }

    @GetMapping("/common/enterprise/riskUnit")
    public TableDataInfo riskUnit(RiskUnit riskUnit)
    {
        startPage();
        List<RiskUnit> riskUnitList = riskUnitService.selectRiskUnitList(riskUnit);
        return getDataTable(riskUnitList);
    }

    @GetMapping("/common/enterprise/surroundingEnv")
    public TableDataInfo surroundingEnv(SurroundingEnv surroundingEnv)
    {
        startPage();
        List<SurroundingEnv> surroundingEnvList = surroundingEnvService.selectSurroundingEnvList(surroundingEnv);
        return getDataTable(surroundingEnvList);
    }





    @GetMapping("/visit/test")
    public AjaxResult test() {
        return AjaxResult.success("");
    }





    @PostMapping("/common/fileMaker")
    public AjaxResult fileMaker(@RequestBody FileMaker fileMaker,HttpServletRequest request){
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String path = request.getContextPath();
        String basePath = scheme + "://" + serverName + ":" + port + path;
        fileMaker.setCreateTime(new Date());
    /*    Integer file_maker_id = fileMaker.getFileId();
        if(fileMaker.getMemberId() ==null || file_maker_id == null) return*/
        String resultFileName = "";
        String resultFilePath = "";

        Map<String, Object> map = new HashMap();
        logger.info("传过来的值是---------"+fileMaker.getWuliandan().toString());
        map.put("${t1}", fileMaker.getWuliandan().get("key1"));//
        map.put("${t2}", fileMaker.getWuliandan().get("key2"));//
        map.put("${t3}", fileMaker.getWuliandan().get("key3"));//
        map.put("${t4}", fileMaker.getWuliandan().get("key4"));//
        map.put("${t5}", fileMaker.getWuliandan().get("key5"));//
        resultFileName = MSWordPoi4.readwriteWord(0,"C:\\software\\develop\\nginx-1.18.0\\html\\file_example\\wuliandan.doc", map);
        if(org.apache.commons.lang.StringUtils.isNotBlank(resultFileName)){

            fileMaker.setFilePath(basePath+resultFileName);
        }

        if(!fileMakerService.save(fileMaker)) return AjaxResult.error();
        resultFilePath = basePath+resultFileName;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileId",fileMaker.getId());
        jsonObject.put("filePath",resultFilePath);
        return AjaxResult.success(jsonObject);
    }


    @GetMapping("/common/largeOne")
    public AjaxResult largeOne(){
        //月全部投诉
        QueryWrapper monthAll =  new QueryWrapper<LetterVisit>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())");
        List<LetterVisit> monthAllList = letterVisitNewService.list(monthAll);
        //季度全部投诉
        QueryWrapper jiduAll =  new QueryWrapper<LetterVisit>().apply("QUARTER( create_time )= QUARTER (curdate())");
        List<LetterVisit> jiduAllList = letterVisitNewService.list(jiduAll);
        //年全部投诉
        QueryWrapper yearAll =  new QueryWrapper<LetterVisit>().apply("YEAR(create_time)=year(curdate())");
        List<LetterVisit> yearAllList = letterVisitNewService.list(yearAll);

        QueryWrapper monthAll_no =  new QueryWrapper<LetterVisit>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())").eq("lv_is_accept",0);
        List<LetterVisit> monthAllList_no = letterVisitNewService.list(monthAll_no);

        QueryWrapper monthAll_yes =  new QueryWrapper<LetterVisit>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())").eq("lv_is_accept",1).or().eq("lv_is_accept",2);
        List<LetterVisit> monthAllList_yes = letterVisitNewService.list(monthAll_yes);

        QueryWrapper jiduAll_no =  new QueryWrapper<LetterVisit>().apply("QUARTER( create_time )= QUARTER (curdate())").eq("lv_is_accept",0);
        List<LetterVisit> jiduAllList_no = letterVisitNewService.list(jiduAll_no);
        QueryWrapper jiduAll_yes =  new QueryWrapper<LetterVisit>().apply("QUARTER( create_time )= QUARTER (curdate())").eq("lv_is_accept",1).or().eq("lv_is_accept",2);
        List<LetterVisit> jiduAllList_yes = letterVisitNewService.list(jiduAll_yes);

        QueryWrapper yearAll_no  =  new QueryWrapper<LetterVisit>().apply("YEAR(create_time)=year(curdate())").eq("lv_is_accept",0);
        List<LetterVisit> yearList_no = letterVisitNewService.list(yearAll_no);
        QueryWrapper yearAll_yes =  new QueryWrapper<LetterVisit>().apply("YEAR(create_time)=year(curdate())").eq("lv_is_accept",1).or().eq("lv_is_accept",2);
        List<LetterVisit> yearList_yes = letterVisitNewService.list(yearAll_yes);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("monthAll",monthAllList.size());
        jsonObject.put("jiduAllList",jiduAllList.size());
        jsonObject.put("yearAllList",yearAllList.size());

        jsonObject.put("monthAll_no",monthAllList_no.size());
        jsonObject.put("monthAll_yes",monthAllList_yes.size());

        jsonObject.put("jiduAll_no",jiduAllList_no.size());
        jsonObject.put("jiduAll_yes",jiduAllList_yes.size());

        jsonObject.put("yearAll_no",yearList_no.size());
        jsonObject.put("yearAll_yes",yearList_yes.size());
        return AjaxResult.success(jsonObject);
    }


    @GetMapping("/common/largeTwo")
    public AjaxResult largeTwo(){
        QueryWrapper monthAll =  new QueryWrapper<LetterVisit>().select("DATE_FORMAT(create_time,'%Y-%m') as time,count(1) num").groupBy("create_time");
        List<EnvShouxu> monthAllList = envShouxuNewService.list(monthAll);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("monthAll",monthAllList);
        return AjaxResult.success(jsonObject);
    }


    @GetMapping("/common/enterprise/epCount")
    public AjaxResult getEpCount(){
        //月
        QueryWrapper maying_month =  new QueryWrapper<EnterpriseArchive>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())").eq("ep_area",610310);

        QueryWrapper bayu_month =  new QueryWrapper<EnterpriseArchive>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())").eq("ep_area",610311);

        QueryWrapper diaowei_month =  new QueryWrapper<EnterpriseArchive>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())").eq("ep_area",610312);

        QueryWrapper tianwang_month =  new QueryWrapper<EnterpriseArchive>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())").eq("ep_area",610313);

        QueryWrapper panxi_month =  new QueryWrapper<EnterpriseArchive>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())").eq("ep_area",610314);

        QueryWrapper qianhe_month =  new QueryWrapper<EnterpriseArchive>().apply("MONTH ( create_time ) = MONTH (curdate())" +
                " AND YEAR ( create_time ) = YEAR (curdate())").eq("ep_area",610315);

        List<EnterpriseArchive> myMonthList = epNewService.list(maying_month);
        List<EnterpriseArchive> byMonthList = epNewService.list(bayu_month);
        List<EnterpriseArchive> dwMonthList = epNewService.list(diaowei_month);
        List<EnterpriseArchive> twMonthList = epNewService.list(tianwang_month);
        List<EnterpriseArchive> pxMonthList = epNewService.list(panxi_month);
        List<EnterpriseArchive> qhMonthList = epNewService.list(qianhe_month);


        //季度
        QueryWrapper my_jidu =  new QueryWrapper<EnterpriseArchive>().apply("QUARTER( create_time )= QUARTER (curdate())").eq("ep_area",610310);
        QueryWrapper by_jidu =  new QueryWrapper<EnterpriseArchive>().apply("QUARTER( create_time )= QUARTER (curdate())").eq("ep_area",610311);
        QueryWrapper dw_jidu =  new QueryWrapper<EnterpriseArchive>().apply("QUARTER( create_time )= QUARTER (curdate())").eq("ep_area",610312);
        QueryWrapper tw_jidu =  new QueryWrapper<EnterpriseArchive>().apply("QUARTER( create_time )= QUARTER (curdate())").eq("ep_area",610313);
        QueryWrapper px_jidu =  new QueryWrapper<EnterpriseArchive>().apply("QUARTER( create_time )= QUARTER (curdate())").eq("ep_area",610314);
        QueryWrapper qh_jidu =  new QueryWrapper<EnterpriseArchive>().apply("QUARTER( create_time )= QUARTER (curdate())").eq("ep_area",610315);


        List<EnterpriseArchive> myJiduList = epNewService.list(my_jidu);
        List<EnterpriseArchive> byJiduList = epNewService.list(by_jidu);
        List<EnterpriseArchive> dwJiduList = epNewService.list(dw_jidu);
        List<EnterpriseArchive> twJiduList = epNewService.list(tw_jidu);
        List<EnterpriseArchive> pxJiduList = epNewService.list(px_jidu);
        List<EnterpriseArchive> qhJiduList = epNewService.list(qh_jidu);


        //年
        QueryWrapper myYear =  new QueryWrapper<EnterpriseArchive>().apply("YEAR(create_time)=year(curdate())").eq("ep_area",610310);
        QueryWrapper byYear =  new QueryWrapper<EnterpriseArchive>().apply("YEAR(create_time)=year(curdate())").eq("ep_area",610311);
        QueryWrapper dwYear =  new QueryWrapper<EnterpriseArchive>().apply("YEAR(create_time)=year(curdate())").eq("ep_area",610312);
        QueryWrapper twYear =  new QueryWrapper<EnterpriseArchive>().apply("YEAR(create_time)=year(curdate())").eq("ep_area",610313);
        QueryWrapper pxYear =  new QueryWrapper<EnterpriseArchive>().apply("YEAR(create_time)=year(curdate())").eq("ep_area",610314);
        QueryWrapper qhYear =  new QueryWrapper<EnterpriseArchive>().apply("YEAR(create_time)=year(curdate())").eq("ep_area",6103105);

        List<EnterpriseArchive> myYearList = epNewService.list(myYear);
        List<EnterpriseArchive> dyYearList = epNewService.list(byYear);
        List<EnterpriseArchive> dwYearList = epNewService.list(dwYear);
        List<EnterpriseArchive> twYearList = epNewService.list(twYear);
        List<EnterpriseArchive> pxYearList = epNewService.list(pxYear);
        List<EnterpriseArchive> qhYearList = epNewService.list(qhYear);



        JSONObject jsonObject = new JSONObject();
        jsonObject.put("myMonthCount",myMonthList.size());
        jsonObject.put("byMonthCount",byMonthList.size());
        jsonObject.put("dwMonthCount",dwMonthList.size());
        jsonObject.put("twMonthCount",twMonthList.size());
        jsonObject.put("pxMonthCount",pxMonthList.size());
        jsonObject.put("qhMonthCount",qhMonthList.size());


        jsonObject.put("myJiduCount",myJiduList.size());
        jsonObject.put("byJiduCount",byJiduList.size());
        jsonObject.put("dwJiduCount",dwJiduList.size());
        jsonObject.put("twJiduCount",twJiduList.size());
        jsonObject.put("pxJiduCount",pxJiduList.size());
        jsonObject.put("qhJiduCount",qhJiduList.size());


        jsonObject.put("myYearCount",myYearList.size());
        jsonObject.put("byYearCount",dyYearList.size());
        jsonObject.put("dwYearCount",dwYearList.size());
        jsonObject.put("twYearCount",twYearList.size());
        jsonObject.put("pxYearCount",pxYearList.size());
        jsonObject.put("qhYearCount",qhYearList.size());

        return AjaxResult.success(jsonObject);
    }







    @GetMapping("/common/province")
    public AjaxResult getProvince(HttpServletRequest request){
        List<Map<String, Object>> mapData = sysChinaService.getCityTree();
        return AjaxResult.success(mapData);
    }


    @GetMapping("/common/china")
    public AjaxResult getChina(@RequestParam("epProvince") String epProvince){
        System.out.println("省的ID+++++++++++++++"+epProvince);
        if(StringUtils.isEmpty(epProvince)){
            return AjaxResult.error("还没获取到省级数据，请重新获取");
        }
        Integer xxx = Integer.parseInt(epProvince);
        List<Map<String, Object>> mapData = sysChinaService.getChild(xxx);
        return AjaxResult.success(mapData);
    }



    @GetMapping("/common/industry")
    public AjaxResult getIndustry(){
        return AjaxResult.success(industryService.getIndustryData());
    }


    @GetMapping("/common/industryById")
    public AjaxResult getIndustryById(@RequestParam String id){
        return AjaxResult.success(industryService.getIndustryById(id));
    }

    @PostMapping("/common/industryAll")
    public AjaxResult getIndustryAll( @RequestBody Map<String, Object> params){
        System.out.println("----------------------------------------------"+params.get("page").toString()+"------------------------------------------"+params.get("size").toString());
        //List<Map<String,Object>> resultMap = industryService.getIndustryAllData(params);
        IPage<IndustryEntity> resultMap= industryService.getIndustryAllData(params);
        return AjaxResult.success(resultMap);
    }

    @PostMapping("/common/industry/save")
    public AjaxResult saveIndustry(@RequestBody IndustryEntity industryEntity){
        return AjaxResult.success( industryService.save(industryEntity));
    }

    @PostMapping("/common/industry/update")
    public AjaxResult updateIndustry(@RequestBody IndustryEntity industryEntity){
        return AjaxResult.success( industryService.updateById(industryEntity));
    }

    @PostMapping("/common/industry/delete")
    public AjaxResult deleteIndustry(@RequestBody IndustryEntity industryEntity){
        return AjaxResult.success( industryService.removeById(industryEntity));
    }


    @RequestMapping("/common/sendMessage")
    public AjaxResult sendMessage(@RequestParam("phone") String phone, @RequestParam("template") int template) {
        logger.info("发送短信接口被调用{}", phone);
        String redisKey = "redis:mobile:" + phone;
        String redisTimeKey = "redis:mobile:" + phone;
        String redisTimeExist = String.valueOf(redisTemplate.opsForValue().get(redisTimeKey));
        logger.info("redisTime {}", redisTimeExist);
        //判断超时
        if (StringUtils.isNotNull(redisTimeExist) && StringUtils.isEmpty(redisTimeExist)) {
            logger.info("redisTime  {}", redisTimeExist);
            long oldTime = Long.parseLong(redisTimeExist);
            if (System.currentTimeMillis() - oldTime < 60000) {
                return AjaxResult.error("验证码已发送");
            }
        }
        String strCode = getRandom(6);
        redisTemplate.opsForValue().set(redisTimeKey, String.valueOf(System.currentTimeMillis()), 10, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(redisKey, strCode, 10, TimeUnit.MINUTES);
        //调用短信接口
        boolean result = smsSerivce.send(MessageTemplate.getTemplate(template), phone,"LTAI5tPBh4KMK9V4qgCL5ocZ","BoaxQr1nfu5dr6tqFjak7LfOogDwiS",strCode);
        logger.info("调用短信发送接口，返回结果:{}", result);
        if(result){
            return AjaxResult.success(strCode);
        }
        return AjaxResult.error("发送失败",result);
    }

    public static String getRandom(int length) {
        String base = "123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    @PostMapping("/common/fogetPwd")
    public AjaxResult fogetPwd(@RequestBody SysUser sysUser) {
        String redisKey = "redis:mobile:" + sysUser.getPhonenumber();
        String codeNumber = String.valueOf(redisTemplate.opsForValue().get(redisKey));
        logger.info("忘记密码 redis里验证码:{}", codeNumber);
        logger.info("忘记密码 传过来的验证码:{}", sysUser.getVildateCode());
        if (StringUtils.isBlank(codeNumber) || !sysUser.getVildateCode().equals(codeNumber)) return AjaxResult.error("验证码错误");
        List<SysUser> oldSysUserList = userService.selectUserList(sysUser);
        if(CollectionUtils.isEmpty(oldSysUserList)) return AjaxResult.error("用户不存在");
        SysUser oldSysUser = oldSysUserList.get(0);
        oldSysUser.setUpdateTime(new Date());
        oldSysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        return userService.updateUserProfile(oldSysUser) > 0 ? AjaxResult.success() : AjaxResult.error("密码更新失败");
    }

}
